package org.example.rowing.controller;


import javafx.fxml.FXML;
import javafx.scene.control.Alert;
import javafx.scene.control.PasswordField;
import javafx.scene.control.TextField;
import javafx.stage.Stage;
import lombok.extern.slf4j.Slf4j;
import org.example.rowing.controller.util.NavigationUtil;
import org.example.rowing.domain.User;
import org.example.rowing.service.LoginService;
import org.example.rowing.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.io.IOException;

@Controller
@Slf4j
public class LoginController {
    @FXML
    private TextField usernameField;
    @FXML
    private PasswordField passwordField;

    @Autowired
    private LoginService loginService;
    @Autowired
    private UserService userService;

    @FXML
    private void handleLogin() {
        String username = usernameField.getText();
        String password = passwordField.getText();

        if(username.isEmpty() || password.isEmpty()) {
            showAlert("输入错误", "用户名和密码不能为空");
            return;
        }

        if(loginService.validateUser(username, password)) {
            User user = userService.showUserByName(username);
            if(user.getRequirePasswordChange()) {
                showChangePasswordView();
            } else {
                showMainApplication();
            }
        } else {
            showAlert("登录失败","用户名或密码错误");
        }
    }

    @FXML
    private void handleChangePassword() {
        // 跳转到修改密码界面
        showChangePasswordView();
    }

    private void showMainApplication() {
        Stage stage = (Stage) usernameField.getScene().getWindow();
        try {
            NavigationUtil.navigateToScene(stage, "/fxml/HomeView.fxml", "赛艇赛事管理系统");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showChangePasswordView() {
        try {
            Stage stage = (Stage) usernameField.getScene().getWindow();
            NavigationUtil.navigateToScene(stage,
                    "/fxml/ChangePasswordView.fxml",
                    "赛艇赛事管理系统",
                    controller -> {
                        if (controller instanceof ChangePasswordController) {
                            ((ChangePasswordController) controller).initialize(usernameField.getText());
                        }
                    });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private void showAlert(String title, String message) {
        Alert alert = new Alert(Alert.AlertType.WARNING);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(message);
        alert.showAndWait();
    }
}
